﻿using System;
using nRoute.Components;
using nRoute.Components.Composition;

namespace Orktane.ScriptActionModel
{
    public class DefaultScriptActionLocator 
        : IResourceLocator
    {
        private readonly ScriptActionMeta _meta;
        private readonly Object _lock = new Object();
        private IScriptAction _instance;

        public DefaultScriptActionLocator(ScriptActionMeta meta)
        {
            if (meta == null) throw new ArgumentNullException("meta");
            _meta = meta;
        }

#region IResourceLocator Members

        public string ResourceName
        {
            get { return _meta.Prefix; }
        }

        public Object ResourceMeta
        {
            get { return _meta; }
        }

        public virtual object GetResourceInstance()
        {
            if (_meta.Lifetime == InstanceLifetime.Singleton)
            {
                // we hold a single instance
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = CreateScriptActionHandlerInstance();
                        }
                    }
                }
                return _instance;
            }
            else
            {
                // always return a new instance
                return CreateScriptActionHandlerInstance();
            }
        }

#endregion

#region IDisposable Members

        public virtual void Dispose()
        {
            lock (_lock)
            {
                if (_instance != null)
                {
                    _instance = null;
                }
            }
        }

#endregion

#region Helpers
		
		protected virtual IScriptAction CreateScriptActionHandlerInstance()
		{
            return (IScriptAction)TypeBuilder.BuildType(_meta.ImplementationType);			
		}
		
#endregion

    }
}